package com.relsell.model;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import com.relsell.controller.DataInterface;
import com.relsell.controller.ParserInterface;
import com.relsell.model.RecentBassLessonsParserImpl.GetBassSongLessonsFromMemory;
import com.relsell.model.RecentBassLessonsParserImpl.GetJSONDataFromURL;
import com.relsell.utility.ApplicationVars;
import com.relsell.view.phone.RecentBassLessons;
import com.relsell.view.phone.RecentBollywoodSongs;

public class RecentBollywoodLessonsParserImpl implements ParserInterface {

	private int mScreen = -1;
	private ArrayList<DataInterface> mDataList;
	public static final int LOADEDJSONDATAFROMURL = 1;
	public static final int READJSONDATAFROMMEMORY = 2;
	private String mResultOfReading;
	private Context mContext;

	public RecentBollywoodLessonsParserImpl(int screen, Context context) {
		mScreen = screen;
		this.mContext = context;
		ApplicationVars.getInstance().setRecentBollyWoodSongsList(
				new ArrayList<DataInterface>());
		mDataList = ApplicationVars.getInstance().getRecentBollyWoodSongsList();
	}

	@Override
	public DataInterface getRelevantDataInterface(int screen) {

		if (mScreen == 0) {
			return new InstructorsDataModel();
		} else if (mScreen == 1) {
			return new InstructorsDataModel();
		} else if (mScreen == 4) {
			return new RecentSongLessonsModel();
		} else if (mScreen == 5) {
			return new RecentBassLessonsModel();
		} else if (mScreen == 6) {
			return new RecentGuitarLessonsModel();
		} else if (mScreen == 7) {
			return new RecentBollywoodLessonsModel();
		} else {

			return null;
		}
	}

	public Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			int whatMessage = msg.what;
			switch (whatMessage) {
			case LOADEDJSONDATAFROMURL:
				String fileName = msg.obj.toString();
				readFromMemory(fileName);
				break;
			case READJSONDATAFROMMEMORY:
				String responseJson = null;
				responseJson = msg.obj.toString();
				new GetBollywoodSongLessonsFromMemory().execute(responseJson);
				break;
			}
		}

	};

	@Override
	public void startParsingJsonData(Context context, boolean isDataNeeded,
			String fileName, String fileURL) throws IOException {

		if (isDataNeeded == true) {
			loadJSONFromURL(context, fileName, fileURL);
		} else {
			readFromMemory(fileName);
		}

	}

	@Override
	public void readFromMemory(String fileName) {
		mResultOfReading = null;
		new AsyncTask<String, Void, String>() {

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				Message msg = new Message();
				msg.obj = result;
				msg.what = READJSONDATAFROMMEMORY;
				mHandler.sendMessage(msg);
			}

			@Override
			protected String doInBackground(String... params) {
				int receiveChars = -1;
				String response = "";
				StringBuilder buf1 = new StringBuilder();
				BufferedReader bufferedReader = null;
				File file = new File(Environment.getExternalStorageDirectory()
						.getAbsolutePath() + "/torrins_data/" + params[0]);
				InputStream ins = null;
				try {
					ins = new FileInputStream(file);
					bufferedReader = new BufferedReader(new InputStreamReader(
							ins, "UTF-8"));
					char[] bufferOne = new char[1024 * 500];
					// This will take time since 2MB of data is to be read in
					// buffer
					while ((receiveChars = bufferedReader.read(bufferOne)) != -1) {
						buf1.append(bufferOne);
					}
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return buf1.toString();
			}

		}.execute(fileName);
	}

	@Override
	public boolean writeToMemory(Context context, String fileName,
			String fileURL) throws IOException {

		boolean result = false;
		HttpURLConnection connection = null;
		URL url = null;
		try {

			url = new URL(fileURL);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.connect();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		File folderDir = null;
		folderDir = new File(Environment.getExternalStorageDirectory()
				+ "/torrins_data");
		if (!folderDir.isDirectory()) {
			folderDir.mkdirs();
		}
		File file = new File(folderDir, fileName);
		if (!file.exists()) {
			file.createNewFile();
		}

		try {
			InputStream inputStream = connection.getInputStream();
			BufferedInputStream bufferedInputStream = null;

			bufferedInputStream = new BufferedInputStream(inputStream, 1024 * 5);

			FileOutputStream fileOutputStream = new FileOutputStream(folderDir
					+ "/" + fileName);
			byte[] buffer = new byte[1024];
			int len1 = 0;
			while ((len1 = inputStream.read(buffer)) != -1) {
				fileOutputStream.write(buffer, 0, len1);
			}

			bufferedInputStream.close();

			fileOutputStream.close();
			inputStream.close();
			connection.disconnect();
			result = true;
		} catch (Exception e) {
			result = false;
			e.printStackTrace();
		}

		return result;
	}

	@Override
	public String loadJSONFromAsset(Context context) {
		String json = null;
		try {

			InputStream is = context.getAssets().open("instructors.json");

			int size = is.available();

			byte[] buffer = new byte[size];

			is.read(buffer);

			is.close();

			json = new String(buffer, "UTF-8");

		} catch (IOException ex) {
			ex.printStackTrace();
			return null;
		}
		return json;

	}

	public class GetJSONDataFromURL extends AsyncTask<String, Void, Boolean> {

		private Context mContext;
		private String fileName;
		private String fileURL;

		public GetJSONDataFromURL(Context context, String fileName,
				String fileURL) {
			this.mContext = context;
			this.fileName = fileName;
			this.fileURL = fileURL;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			Message msg = new Message();
			msg.what = LOADEDJSONDATAFROMURL;
			msg.obj = fileName;
			mHandler.sendMessage(msg);
		}

		@Override
		protected Boolean doInBackground(String... params) {
			Boolean responseString = false;
			try {
				if (writeToMemory(mContext, fileName, fileURL)) {
					responseString = true;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			return responseString;
		}

	}

	@Override
	public void loadJSONFromURL(Context context, String fileName, String fileURL) {
		new GetJSONDataFromURL(context, fileName, fileURL).execute();

	}

	public class GetBollywoodSongLessonsFromMemory extends
			AsyncTask<String, Void, Boolean> {

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (result == true) {
				Message msg = new Message();
				msg.what = RecentBollywoodSongs.GOT_DATA_FOR_RECENT_BOLLYWOOD_LESSON;
				ApplicationVars.getInstance().getHandler().sendMessage(msg);
			}
		}

		@Override
		protected Boolean doInBackground(String... jsonData) {
			boolean result = false;
			try {
				JSONObject obj = new JSONObject(jsonData[0]);
				JSONArray listArray = (JSONArray) obj.getJSONArray("list");
				int size = listArray.length();
				
				
				DataInterface localObj = null;
				for (int i = 0; i < size; i++) {
					localObj = getRelevantDataInterface(mScreen);
					
					if (localObj instanceof RecentBollywoodLessonsModel) {
						String title = ((JSONObject)(listArray.get(i))).getString("title");
						String artist = ((JSONObject)(listArray.get(i))).getString("artist");
						String created = ((JSONObject)(listArray.get(i))).getString("created");

						((RecentBollywoodLessonsModel) localObj).setTitle(title);
						((RecentBollywoodLessonsModel) localObj)
								.setArtist(artist);
						((RecentBollywoodLessonsModel) localObj).setCreated(created);
					}
					mDataList.add(localObj);
				}
				result = true;
			} catch (JSONException e) {
				e.printStackTrace();
				result = false;
			}
			return true;

		}

	}

	public boolean isNameUnique(String name, ArrayList<JSONObject> list)
			throws JSONException {
		boolean result = true;
		for (JSONObject localObj : list) {
			if (name.equals(localObj.get("title").toString())) {
				result = false;
				break;
			}
		}
		return result;
	}

}
